package com.zjeav.lingjiao.ui.music;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.animation.AnimationUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.zjeav.lingjiao.R;
import com.zjeav.lingjiao.base.baseBean.LocalMetadata;
import com.zjeav.lingjiao.base.tools.LrcInfo;
import com.zjeav.lingjiao.base.tools.LrcList;
import com.zjeav.lingjiao.base.tools.LrcParse;
import com.zjeav.lingjiao.base.tools.Mp3Info;
import com.zjeav.lingjiao.base.tools.PlayerMSG;
import com.zjeav.lingjiao.base.tools.SharedPreferencesUtils;
import com.zjeav.lingjiao.ui.lrc.ILrcBuilder;
import com.zjeav.lingjiao.ui.lrc.ILrcViewItemClickListener;
import com.zjeav.lingjiao.ui.lrc.ILrcViewListener;
import com.zjeav.lingjiao.ui.lrc.impl.DefaultLrcBuilder;
import com.zjeav.lingjiao.ui.lrc.impl.LrcRow;


public class MusicService extends Service {

    // mp3的绝对路径
    private String path;
    private String lrc_string;
    //当前播放位置
    private int position;
    //当前播放进度
    private int currentTime;
    List<LrcRow> rows;
    private int msg;                //播放信息

    private boolean isPause;
    //更新歌词的频率，每秒更新一次
    private int mPalyTimerDuration = 1000;
    //更新歌词的定时器
    private Timer mTimer;
    //更新歌词的定时任务
    private TimerTask mTask;

    static List<LocalMetadata> mp3Infos;    //存放Mp3Info对象的集合

    private int duration;            //播放长度
    private String TAG = "时长";

    private LrcInfo lrcInfo;        //歌词信息
    private ArrayList<LrcList> lrcLists;    //存放歌词的结点信息

    int palyflag = 0;               //播放的标志

    int index;                      //歌词索引


    //服务要发送的一些Action
    public static final String UPDATE_ACTION = "com.flashmusic.action.UPDATE_ACTION";  //更新音乐播放曲目
    public static final String CTL_ACTION = "com.flashmusic.action.CTL_ACTION";        //控制播放模式
    public static final String MUSIC_CURRENT = "com.flashmusic.action.MUSIC_CURRENT";  //当前音乐播放时间更新
    public static final String MUSIC_DURATION = "com.flashmusic.action.MUSIC_DURATION";//播放音乐长度更新
    public static final String PLAY_STATUE = "com.flashmusic.action.PLAY_STATUE";      //更新播放状态
    public static final String SHOW_LRC = "com.flashmusic.action.SHOW_LRC";            //通知显示歌词
    //播放音乐的媒体类
    MediaPlayer mediaPlayer;

    IBinder musicBinder = new MyBinder();

    //handler用来接收消息，来发送广播更新播放时间
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (mediaPlayer != null) {
                        if (mediaPlayer.isPlaying()){
                            currentTime = mediaPlayer.getCurrentPosition();
                            Intent intent = new Intent();
                            intent.setAction(MUSIC_CURRENT);
                            intent.putExtra("currentTime", currentTime);
                            Log.e(TAG, "当前时间" + currentTime);
                            sendBroadcast(intent); // 给PlayerActivity发送广播
                            SharedPreferencesUtils.setParam(getApplicationContext(),"currentTime",currentTime);
                            mHandler.sendEmptyMessageDelayed(1, 1000);
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };

    class MyBinder extends Binder {
        public Service getService() {
            return MusicService.this;
        }
    }


    @Override
    public void onCreate() {
        super.onCreate();

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                Log.e("Err", "i" + i + "i1" + i1);
                return true;
            }
        });

        /**
         * 设置音乐播放完成时的监听器
         */
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.e(TAG, "播放完时的时长：" + mediaPlayer.getDuration());
                Intent intent = new Intent(PLAY_STATUE);
                // 发送播放完毕的信号，更新播放状态
                intent.putExtra("playstatue", false);
                sendBroadcast(intent);
                SharedPreferencesUtils.setParam(getApplicationContext(),"currentTime",0);
                if (palyflag == 2) {
                    Intent loopintent = new Intent(PLAY_STATUE);
                    // 发送播放完毕的信号，更新播放状态
                    intent.putExtra("playstatue", true);
                    sendBroadcast(loopintent);
                    // 单曲循环
                    mediaPlayer.start();

                } else if (palyflag == 1) {
                    // 列表循环
                    position++;
                    if (position > mp3Infos.size() - 1) {
                        //变为第一首的位置继续播放
                        position = 0;
                    }
                    Intent sendIntent = new Intent(UPDATE_ACTION);
                    sendIntent.putExtra("position", position);
                    // 发送广播，将被MusicActivity组件中的BroadcastReceiver接收到
                    sendBroadcast(sendIntent);
                    path = mp3Infos.get(position).getUrl();
                    play(0);
                } else if (palyflag == 0) { // 顺序播放
//                    position++;    //下一首位置

//                    mediaPlayer.seekTo(0);
////                    position = 0;
//                    Intent sendIntent = new Intent(UPDATE_ACTION);
//                    sendIntent.putExtra("position", position);
//                    // 发送广播，将被Activity组件中的BroadcastReceiver接收到
//                    sendBroadcast(sendIntent);
                } else if (palyflag == 3) {    //随机播放
                    position = getRandomIndex(mp3Infos.size() - 1);
                    Intent sendIntent = new Intent(UPDATE_ACTION);
                    sendIntent.putExtra("position", position);
                    // 发送广播，将被Activity组件中的BroadcastReceiver接收到
                    sendBroadcast(sendIntent);
                    path = mp3Infos.get(position).getUrl();
                    play(0);
                }

            }
        });


    }

    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            path = intent.getStringExtra("url");        //歌曲路径
            position = intent.getIntExtra("position", -1);    //当前播放歌曲的在mp3Infos的位置
            msg = intent.getIntExtra("MSG", 0);            //播放信息
            if (msg == PlayerMSG.MSG.PLAY_MSG) {    //直接播放音乐
                play(0);
            } else if (msg == PlayerMSG.MSG.PAUSE_MSG) {    //暂停
                pause();
                Intent intentstatus = new Intent();
                intentstatus.setAction(PLAY_STATUE);
                duration = mediaPlayer.getDuration();
                intentstatus.putExtra("playstatue", false);    //通过Intent来传递歌曲的总长度
                sendBroadcast(intentstatus);
            } else if (msg == PlayerMSG.MSG.STOP_MSG) {        //停止
                stop();
                Intent intentstatus = new Intent();
                intentstatus.setAction(PLAY_STATUE);
                duration = mediaPlayer.getDuration();
                intentstatus.putExtra("playstatue", false);    //通过Intent来传递歌曲的总长度
                sendBroadcast(intentstatus);
            } else if (msg == PlayerMSG.MSG.CONTINUE_MSG) {    //继续播放
                resume();
            } else if (msg == PlayerMSG.MSG.PRIVIOUS_MSG) {    //上一首
                previous();
            } else if (msg == PlayerMSG.MSG.NEXT_MSG) {        //下一首
                next();
            } else if (msg == PlayerMSG.MSG.PROGRESS_CHANGE) {    //进度更新
                currentTime = intent.getIntExtra("progress", -1);
                play(currentTime);
            } else if (msg == PlayerMSG.MSG.PLAYING_MSG) {
                mHandler.sendEmptyMessage(1);
            }
        }
        return super.onStartCommand(intent, Service.START_REDELIVER_INTENT, startId);
    }

    private void play(int currentTime) {
        try {

            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.reset();// 把各项参数恢复到初始状态
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepareAsync(); // 进行缓冲
//            Thread.sleep(2000);
            mediaPlayer.setOnPreparedListener(new PreparedListener(currentTime));// 注册一个监听器
            initLrc();
            //更新播放状态
            Intent intent = new Intent(PLAY_STATUE);
            // 发送播放完毕的信号，更新播放状态
            intent.putExtra("playstatue", true);
            sendBroadcast(intent);
//            mHandler.sendEmptyMessage(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //继续播放
    private void resume() {
        if (isPause) {
            isPause = false;
        }else {
            mediaPlayer.pause();
        }
        mediaPlayer.start();
    }

    /**
     * 上一首
     */
    private void previous() {
        Intent sendIntent = new Intent(UPDATE_ACTION);
        sendIntent.putExtra("position", position);
        // 发送广播，将被Activity组件中的BroadcastReceiver接收到
        sendBroadcast(sendIntent);
        play(0);
    }

    /**
     * 下一首
     */
    private void next() {
        mediaPlayer.seekTo(0);
        Intent sendIntent = new Intent(UPDATE_ACTION);
        sendIntent.putExtra("position", position);
        // 发送广播，将被Activity组件中的BroadcastReceiver接收到
        sendBroadcast(sendIntent);
        play(0);
    }

    private void pause() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            isPause = true;
        }
    }

    private void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            try {
                mediaPlayer.prepare(); // 在调用stop后如果需要再次通过start进行播放,需要之前调用prepare函数
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 实现一个OnPrepareLister接口,当音乐准备好的时候开始播放
     */
    private final class PreparedListener implements MediaPlayer.OnPreparedListener {
        private int currentTime;

        public PreparedListener(int currentTime) {
            this.currentTime = currentTime;
        }

        @Override
        public void onPrepared(MediaPlayer mp) {


            mediaPlayer.start(); // 开始播放
            if (currentTime > 0) { // 如果音乐不是从头播放
                mediaPlayer.seekTo(currentTime);
            }
            Intent intent = new Intent();
            intent.setAction(MUSIC_DURATION);
            duration = mediaPlayer.getDuration();
            intent.putExtra("duration", duration);    //通过Intent来传递歌曲的总长度
            Log.e(TAG, "准备好的时长:" + duration + "");
            sendBroadcast(intent);
            mHandler.sendEmptyMessage(1);


        }
    }

    protected int getRandomIndex(int end) {
        int index = (int) (Math.random() * end);
        return index;
    }

    public void initLrc() {

//        //建立歌词对象
//        LrcParse lrcParser = new LrcParse(path);
//        //读歌词，并将数据传给歌词信息类
//        lrcInfo = lrcParser.readLrc();
//        //获得歌词中的结点
//        lrcLists = lrcInfo.getLrcLists();
//        //在musicActivity里面设置静态来共享数据
//        MusicActivity.lrcView.setmLrcList(lrcInfo);
//        //切换带动画显示歌词
//        MusicActivity.lrcView.setAnimation(AnimationUtils.loadAnimation(MusicService.this, R.anim.alpha_z));
//        mHandler.post(mRunnable);

        ///------------------------------
        String lrc_path = path.replace(".mp3", ".lrc");
//        new Thread(readRunnable).start();

        String lrc = getFromSD(lrc_path);
        if (!lrc.equals("")) {
            //解析歌词构造器
            ILrcBuilder builder = new DefaultLrcBuilder();
            //解析歌词返回LrcRow集合

            rows = builder.getLrcRows(lrc);
            //将得到的歌词集合传给mLrcView用来展示
            MusicActivity.lrcView.setLrc(rows);
            MusicActivity.lrcView.setAnimation(AnimationUtils.loadAnimation(MusicService.this, R.anim.alpha_z));
        }
//        mHandler.post(runnable);

        //设置自定义的LrcView上下拖动歌词时监听
        MusicActivity.lrcView.setListener(new ILrcViewListener() {
            //当歌词被用户上下拖动的时候回调该方法,从高亮的那一句歌词开始播放
            public void onLrcSeeked(int newPosition, LrcRow row) {
                if (mediaPlayer != null) {
                    if (!mediaPlayer.isPlaying()){
                        mediaPlayer.start();
                        mediaPlayer.seekTo((int) row.time);
                        Intent intent = new Intent(PLAY_STATUE);
                        // 发送播放完毕的信号，更新播放状态
                        intent.putExtra("playstatue", true);
                        sendBroadcast(intent);
                        mHandler.sendEmptyMessage(1);
                    }else {
                        mediaPlayer.seekTo((int) row.time);
                    }
                    Log.d("", "onLrcSeeked:" + row.time);
//                    mPlayer.seekTo((int) row.time);

                }
            }
        });
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
//            MusicActivity.lrcView.seekLrc(lrcIndex(),true);
            MusicActivity.lrcView.seekLrcToTime(currentTime);
            MusicActivity.lrcView.invalidate();
            mHandler.postDelayed(runnable, 100);
        }
    };

    public int lrcIndex() {
        if (mediaPlayer.isPlaying()) {
            currentTime = mediaPlayer.getCurrentPosition();
            duration = mediaPlayer.getDuration();
        }
        if (currentTime < duration) {
            for (int i = 0; i < rows.size(); i++) {
                if (i < rows.size() - 1) {
                    if (currentTime < rows.get(i).time && i == 0) {
                        index = i;
                    }
                    if (currentTime > rows.get(i).time && currentTime < rows.get(i + 1).time) {
                        index = i;
                    }
                }
                if ((i == rows.size() - 1) && currentTime > rows.get(i).time) {
                    index = i;
                }
            }
        }
        return index;
    }

    /**
     * 从assets目录下读取歌词文件内容
     *
     * @param fileName
     * @return
     */
    public String getFromSD(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(new FileInputStream(new File(fileName)));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String result = "";
            while ((line = bufReader.readLine()) != null) {
                if (line.trim().equals(""))
                    continue;
                result += line + "\r\n";
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        //当绑定后，返回一个musicBinder
        return musicBinder;
    }

    @Override
    public void onDestroy() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        mHandler.removeCallbacksAndMessages(mHandler);
    }
}
